package top.wettis.chat.service.impl;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import top.wettis.chat.constant.ResultType;
import top.wettis.chat.mapper.*;
import top.wettis.chat.pojo.DO.Task;
import top.wettis.chat.pojo.DO.User;
import top.wettis.chat.pojo.Query.UpdateAccount;
import top.wettis.chat.pojo.Query.UserAccount;
import top.wettis.chat.pojo.Query.UserInfo;
import top.wettis.chat.pojo.VO.Result;
import top.wettis.chat.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static top.wettis.chat.pojo.Query.Constant.LOGIN_NICK_NAME;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author wettis
 * @since 2023-03-25
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, StpInterface {
    private final UserMapper userMapper;
    private final PermissionMapper permissionMapper;


    @Autowired
    private ObjectivesMapper objectivesMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TodayPunchMapper todayPunchMapper;

    @Autowired
    private HistoryRecordMapper historyRecordMapper;


    public UserServiceImpl(UserMapper userMapper, PermissionMapper permissionMapper) {
        this.userMapper = userMapper;
        this.permissionMapper = permissionMapper;
    }

    @Override
    public SaResult doLogin(UserAccount userAccount) {
        User user = getBaseMapper().selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, userAccount.getUsername()));
        if (user == null) {
            return SaResult.error("用户不存在");
        }
        if (BCrypt.checkpw(userAccount.getPassword(), user.getPassword())) {
            StpUtil.login(user.getUserId());
            return SaResult.data(StpUtil.getTokenInfo().getTokenValue());
        } else {
            return SaResult.error("密码错误");
        }
    }

    @Override
    public Result<Object> isLogin() {
        if (StpUtil.isLogin()) {
            return Result.customInfo(200, "已登录", true);
        } else {
            return Result.customInfo(200, "未登录", false);
        }
    }

    @Override
    public Result<Object> logout() {
        if (StpUtil.getLoginIdDefaultNull() != null) {
            return Result.customInfo(200, "成功退出登录", null);
        } else {
            return Result.failInfo(ResultType.LOGIN, null);
        }
    }

    @Override
    public Result<Object> tokenInfo() {
        if (StpUtil.getLoginIdDefaultNull() != null) {
            return Result.customInfo(200, String.valueOf(StpUtil.getTokenInfo()), null);
        } else {
            return Result.failInfo(ResultType.LOGIN, null);
        }
    }

    @Override
    @Transactional
    public Result<Object> register(UserAccount userAccount) {
        if (
                getBaseMapper().selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, userAccount.getUsername())) != null
        ) {
            return Result.customInfo(200, "用户名重复", false);
        }

        User newUser = new User() {{
            setUsername(userAccount.getUsername());
            setPassword(DigestUtil.bcrypt(userAccount.getPassword()));
            setCreateTime(DateUtil.now());
        }};
        newUser = initUser(newUser);

        getBaseMapper().insert(newUser);
        return Result.customInfo(200, "注册成功", true);
    }


    @Override
    public List<String> getPermissionList(Object o, String s) {
        return null;
    }

    @Override
    public List<String> getRoleList(Object o, String s) {
        // 获取当前用户的角色信息
        String userPermission = permissionMapper.selectById(StpUtil.getLoginIdAsInt()).getName();
        System.out.println(permissionMapper);
        return new ArrayList<>() {{
            add(userPermission);
        }};
    }


    public Result<Object> deleteUserById(Integer id) {

        getBaseMapper().delete(new LambdaQueryWrapper<User>().eq(User::getUserId, id));
        return Result.customInfo(200, "删除该用户成功", true);
    }


    // 获取所有用户
    public Result<Object> allUsers() {
        List<User> userList = userMapper.selectAllInfo();
        return Result.customInfo(200, "返回成功", userList);
    }

    //初始化用户
    private User initUser(User user) {
        user.setNeckName(LOGIN_NICK_NAME + RandomUtil.randomNumbers(7));
        user.setAsktimes(0);
        user.setConsecutive(0);
        user.setPunchtimes(0);
        user.setPoint(0);
        user.setLevel(1);
        return user;
    }


    public Result<Object> selectById(Integer id) {
        User user = userMapper.selectByOneId(id);
        return Result.customInfo(200, "查询成功", user);
    }

    //删除该用户包括计划
    public Result<Object> deleteall(Integer id) {
        historyRecordMapper.removeUserById(id);
        taskMapper.removeUserById(id);
        objectivesMapper.removeUserById(id);
        todayPunchMapper.removeUserById(id);
        userMapper.deleteAll(id);
        return Result.customInfo(200, "删除成功", null);
    }

    public Result<Object> inserUserInfo(UpdateAccount updateAccount) {
        try {
            userMapper.insertUserInfo(
                    updateAccount.getPassword()
                    , updateAccount.getUsername()
                    , updateAccount.getNeckName()
                    , updateAccount.getPhone()
                    , updateAccount.getRole()
            );
            return Result.customInfo(200, "添加成功", null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Result<Object> updatepassword(Integer id) {
        try {
            String s = "admin";
            String bcrypt = DigestUtil.bcrypt(s);
            userMapper.updatepassword(id, bcrypt);
            return Result.customInfo(200, "密码修改成功", null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public boolean add(User user) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        userLambdaQueryWrapper.eq(User::getUserId, user.getUserId());
        User one = this.getOne(userLambdaQueryWrapper);
        if (one == null) {
            user.setLevel(1);
            user.setPassword(DigestUtil.bcrypt(user.getPassword()));
            user.setAsktimes(0);
            user.setCreateTime(DateTime.now().toString());
            user.setHasPlan(0);
            user.setConsecutive(0);
            user.setPoint(0);
            user.setPunchtimes(0);
            this.save(user);
            return true;
        }
        return false;
    }

    @Override
    public boolean userUpdate(User user) {
        user.setPassword(DigestUtil.bcrypt(user.getPassword()));
        return this.updateById(user);
    }


    public List<User> userPage(User user) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.like(user.getNeckName() != null, User::getNeckName, user.getNeckName());
        userLambdaQueryWrapper.like(user.getPhone() != null, User::getPhone, user.getPhone());
        List<User> listUser = this.list(userLambdaQueryWrapper);
        return listUser;
    }
}
